package com.aya.export.finder;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

/**
 * @author ls9527
 * @date 2025/3/2
 */
public class PropertyFinder {


    /**
     * 根据规则链动态获取属性值
     *
     * @param target 目标对象
     * @param rule   规则链（如 "data>page>list"）
     * @return 最终属性值，若中间层级失败则返回null
     */
    public static Object getNestedProperty(Object target, String rule) {
        if (target == null || rule == null) return null;

        String[] properties = rule.split(">");
        Object currentValue = target;

        for (String prop : properties) {
            BeanWrapper wrapper = new BeanWrapperImpl(currentValue);
            if (!wrapper.isReadableProperty(prop)) return null; // 检查属性是否存在‌:ml-citation{ref="3,2" data="citationList"}
            currentValue = wrapper.getPropertyValue(prop);
            if (currentValue == null) break; // 若中间值为null，终止遍历‌:ml-citation{ref="7,3" data="citationList"}
        }
        return currentValue;
    }

    /**
     * 根据规则链动态获取属性值
     *
     * @param target 目标对象
     * @param rule   规则链（如 "data>page>list"）
     * @return 最终属性值，若中间层级失败则返回null
     */
    public static Object setNestedProperty(Object target, String rule, Object value) {
        if (target == null || rule == null) return null;

        String[] properties = rule.split(">");
        Object currentValue = target;

        for (int i = 0; i < properties.length; i++) {
            String prop = properties[i];
            BeanWrapper wrapper = new BeanWrapperImpl(currentValue);
            if (!wrapper.isWritableProperty(prop)) {
                return null; // 检查属性是否存在‌
            }
            wrapper.setPropertyValue(prop, value);
        }
        return currentValue;
    }
}
